package com.byteridge.purpleskills;

import java.io.IOException;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class PuzzleActivity extends Activity {
	TextView question;
	static String URL = "http://purpleskills.com/puzzleservice.svc/GetNextQuestion";
	HttpHelper http_helper;
	JSONHelper jsonHelper;
	JSONObject json_object;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SharedPreferences pref = getApplicationContext().getSharedPreferences("UserCredentials", 0); // 0 - for private mode

		setContentView(R.layout.activity_puzzle);
		http_helper = new HttpHelper(URL);
		question=(TextView)findViewById(R.id.question);
		jsonHelper = new JSONHelper();
		try {
			json_object = new JSONObject();
			JSONObject jo = new JSONObject();
			jo.put("UserEmail",pref.getString("userEmail",null));
			jo.put("type","UserToken:#");
			jo.put("Token", pref.getString("token",null));
			json_object.put("userToken", jo);
			json_object.put("svgSupport", 3);
			JSONHelper.setJson(json_object);
			Log.d("json", json_object.toString());
		} catch (JSONException e) {
			Log.v("PurpleSkills", "JSONException  "+e.getMessage());
		}
		GetPuzzle getPuzzle=new GetPuzzle();
		getPuzzle.execute((Void)null);
		
		
	
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_puzzle, menu);
		return true;
	}
	private class GetPuzzle extends AsyncTask<Void, Void, String>
	{
		String response = "";
		@Override
		protected String doInBackground(Void... params) {
			try {
				http_helper.HttpRequest();
				response = http_helper.getHttpResponse();
			} catch (ClientProtocolException e) {
				Log.v("PurpleSkills", "ClientProtocolException  "+e.getMessage());
			} catch (ParseException e) {
				Log.v("PurpleSkills", "ParseException  "+e.getMessage());
			} catch (IOException e) {
				Log.v("PurpleSkills", "IOException  "+e.getMessage());
			}
			return response;
		}
		@Override
		protected void onPostExecute(String result) { 
			JSONObject jo = null;
			String question_text = null;

			try {
				jo = new JSONObject(result);
			} catch (JSONException e) {
				Log.v("PurpleSkills", "JSONException  "+e.getMessage());
			}
			try {
				question_text=jo.getJSONObject("d").getJSONObject("WSData").get("QuestionText").toString();
			} catch (JSONException e) {
				Log.v("PurpleSkills", "JSONException  "+e.getMessage());
			}
			Log.v("question", question_text);
			question.setText(question_text);
	}
	}
}
